package com.eduplatform.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;

/**
 * Web MVC 配置
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Value("${file.upload.path:uploads}")
    private String uploadPath;

    /**
     * 添加资源处理器，使上传的文件可以通过URL访问
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 创建上传目录（如果不存在）
        createUploadDirectories();

        // 添加资源处理器，将/uploads/**映射到文件系统中的上传路径
        registry.addResourceHandler("/uploads/**")
                .addResourceLocations("file:" + uploadPath + File.separator);
    }

    /**
     * 创建上传目录（如果不存在）
     */
    private void createUploadDirectories() {
        // 创建主目录
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        // 创建文件目录
        File filesDir = new File(uploadPath + File.separator + "files");
        if (!filesDir.exists()) {
            filesDir.mkdirs();
        }

        // 创建封面目录
        File coversDir = new File(uploadPath + File.separator + "covers");
        if (!coversDir.exists()) {
            coversDir.mkdirs();
        }
    }
}